package BinaryTree.review;

import 其他.DataStructure.TreeNode;
import MyUtils.MHUtils;
import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

public class 序列化 {
    @Test
    public void test(){
        TreeNode root = MHUtils.strToTree("1,2,null,3,null,4,5");
        System.out.println(treeTostr(root));
    }
    /*
        层序 满二叉树！
        没有就null

        每个cur 只管好自己 【这样不会出错！！】
            pt cur.v
            add cur.l/r
        中序栈遍历也是
            每个cur 要么记录下个left
            要么记录好pt left之后有右存右，无下轮pop

            1
          2
        3
      4  5
     */


    public String treeTostr_x1(TreeNode root){
        StringBuilder sb = new StringBuilder();
//        sb.append(root.val+",");
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);


        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.println("cur:"+cur.val);


            sb.append(cur.val+",");

            if(cur.left!=null){
                //有left但没打印
                queue.add(cur.left);
            }else {
                //所以 left打印后 才能 ptnull
                sb.append("null"+",");
            }

            if(cur.right!=null){
                queue.add(cur.right);
            }else {
                sb.append("null,");
            }
        }
        return sb.toString();
    }
    public String treeTostr(TreeNode root){
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        sb.append(root.val+",");
        queue.add(root);

        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();

            if(cur.left!=null){
                queue.add(cur.left);
                sb.append(cur.left.val+",");
            }else {
                sb.append("null,");
            }

            if(cur.right!=null){
                queue.add(cur.right);
                sb.append(cur.right.val+",");
            }else {
                sb.append("null,");
            }
        }
        return sb.toString();
    }
}
